package edu.cmu.cs.cs214.hw9.client.controllers.eventhandlers;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

import edu.cmu.cs.cs214.hw9.client.controllers.BackendCacheAdapter;
import edu.cmu.cs.cs214.hw9.client.controllers.FacelookController;
import edu.cmu.cs.cs214.hw9.client.gui.LoginScreen;
import edu.cmu.cs.cs214.hw9.datatypes.User;

/**
 * Registers a user. 
 */
public class RegistrationHandler extends EventHandler {
	/**
	 * Run the registration request in a separate thread to prevent swing from freezing.
	 */
	private class RegistrationWorker extends SwingWorker<Boolean, Void> {
		private BackendCacheAdapter model;
		private JFrame frame;
		private User user;
		
		/**
		 * Creates a registration request with the provided details.
		 * 
		 * @param user Details of the user to register.
		 */
		public RegistrationWorker(User user) {
			this.user = user;
			model = controller.getModel();
			frame = controller.getFrame();
		}
		
		/**
		 * Register the user in the database.
		 * 
		 * @return true if successful; false otherwise.
		 */
		public Boolean doInBackground() {
			return model.register(user);
		}
		
		/**
		 * Notify the user of the registration results after the database has been updated.
		 */
		public void done() {
			try {
				boolean result = get();
				
				if (result) {
					JOptionPane.showMessageDialog(frame, "Registration successful! You may now login.");
					changeScreen(new LoginScreen());
				} else {
					JOptionPane.showMessageDialog(frame, "Unable to complete registration.", "Registration Error", JOptionPane.ERROR_MESSAGE);
				}
			} catch (Exception e) {
				throw new RuntimeException("Fatal error occured during registration: " + e.getMessage());
			}
		}
	};
	
	/**
	 * Set the current session controller to the provided controller.
	 * 
	 * @param controller Controller to associate with this event handler.
	 */
	public RegistrationHandler(FacelookController controller) { super(controller); }
	
	/**
	 * Create the registration request and run it in an outside thread.
	 * 
	 * @param param Details of the user to register, encapsulated in a User object.
	 */
	public void handleEvent(Object param) {
		RegistrationWorker registrationworker = new RegistrationWorker((User) param);
		registrationworker.execute();
	}

}
